package com.example.demo.ms;

import java.util.concurrent.Semaphore;

public class TestThreadSemaphore {

    /**
     * 让三个线程交替执行
     * @param args
     */
    public static void main(String[] args) {
        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(1);
        Semaphore semaphoreC = new Semaphore(1);

        try {
            semaphoreB.acquire();
            semaphoreC.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            while (true) {
                try {
                    semaphoreA.acquire();
                    System.out.println(Thread.currentThread().getName()+"----->A");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphoreB.release();
                }
            }
        },"线程A").start();

        new Thread(() -> {
            while (true) {
                try {
                    semaphoreB.acquire();
                    System.out.println(Thread.currentThread().getName()+"---->B");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphoreC.release();
                }
            }
        },"线程B").start();

        new Thread(() -> {
            while (true){
                try {
                    semaphoreC.acquire();
                    System.out.println(Thread.currentThread().getName()+"--->C");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphoreA.release();
                }
            }
        },"线程C").start();

    }
}
